package com.tanhua.app.Interceptor;

import cn.hutool.http.HttpStatus;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.pojo.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor extends HandlerInterceptorAdapter {

    // 拦截请求
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1. 获取请求中的token
        String token = request.getHeader("Authorization");

        // 2. token健全
        boolean verifyToken = JwtUtils.verifyToken(token);

        // 3. 校验 判断false，拦截
        if (!verifyToken) {
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }

        // 4. true，将数据添加到线程变量中
        Claims claims = JwtUtils.getClaims(token);
        User user = new User();
        user.setId(Long.parseLong(claims.get("id").toString()));
        user.setMobile(claims.get("mobile").toString());

        UserHolder.set(user);
        return true;

    }


    // 方法结束，清空线程变量中的数据
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
